
//
//  HttpTools.m
//  MIcroBlog
//
//  Created by zhoupengfei on 15/2/12.
//  Copyright (c) 2015年 zpf. All rights reserved.
//

#import "HttpTools.h"
#import "Toast+UIView.h"
//#define KNameSpace  @"http://ws.apache.org/axis2"
//#define KNameSpace  @"http://yourcompany.com"
#define KNameSpace  @"http://webservice.jfinal.flysoft.com"
@implementation HttpTools
+(void)postWithURL:(NSString*)url arrays:(NSArray*)arrays  method:(NSString*)method success:(void(^)(id JSON))success failure:(void(^)(NSError *error))failure{
    NSString *soapMessage = [self stringWithFormatString:arrays method:method];
//    NSLog(@"_______%@",soapMessage);
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    theRequest.timeoutInterval = 30.0;
    
    NSString *msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[soapMessage length]];
    [theRequest addValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    

      [theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSOperationQueue * operationQueue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:theRequest queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            NSString * xml = [self updateData:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] andMethod:method];
//            NSLog(@"_____xml =%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
            dispatch_async(dispatch_get_main_queue(), ^{
             success(xml);
        });

        }else if (connectionError){
        dispatch_async(dispatch_get_main_queue(), ^{
        //请求
              //  [[UIApplication sharedApplication].keyWindow.rootViewController.view makeToast:connectionError.localizedDescription];

 [[UIApplication sharedApplication].keyWindow.rootViewController.view makeToast:@"网络信号不好，请稍后再试"];
                failure(connectionError);
            });
          
        }

    }];
    
}


+(NSString *)updateData:(NSString *)str andMethod:(NSString *)methName
{
    NSString * string = nil;
    if ([methName isEqualToString:@"validationUser"]) {
        NSString *stra = [str stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
        NSString *strb = [stra stringByReplacingOccurrencesOfString:@"<soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\">" withString:@""];
        NSString *strc = [methName stringByAppendingString:@"Response"];
        NSString *strd = [NSString  stringWithFormat:[self defaultStringOne],strc];
        NSString *stre = [strb stringByReplacingOccurrencesOfString: strd withString:@""];
        NSString *strf = [NSString stringWithFormat:[self defaultStringTwo],strc];
        NSString *strg = [stre stringByReplacingOccurrencesOfString:strf withString:@""];
        string = [strg substringFromIndex:38];
    }else if ([methName isEqualToString:@"tansactionarchivePage"]||[methName isEqualToString:@"tansactiontoybPage"]||[methName isEqualToString:@"toarchivePage"]||[methName isEqualToString:@"tozbPage"]||[methName isEqualToString:@"todoPage"] ||[methName isEqualToString:@"tansactiontodoPage"]|| [methName isEqualToString:@"tozbPage"] || [methName isEqualToString:@"dipatchPage"] ||[methName isEqualToString:@"outboxPage"] || [methName isEqualToString:@"mailPage"] || [methName isEqualToString:@"electronicsPage"] || [methName isEqualToString:@"infojbPage"] ||[methName isEqualToString:@"inPage"] || [methName isEqualToString:@"contentDipatch"] || [methName isEqualToString:@"contentIn"] || [methName isEqualToString:@"contentInfoBriefing"] || [methName isEqualToString:@"contentMail"] || [methName isEqualToString:@"returnTree"] || [methName isEqualToString:@"sendMail"] || [methName isEqualToString:@"roamHistory"] || [methName isEqualToString:@"contentElectronics"] || [methName isEqualToString:@"lookRecord"]||[methName isEqualToString:@"contentTxl"]||
    [methName isEqualToString:@"messageSend"]|| [methName isEqualToString:@"getOaOffice"] ||[methName isEqualToString:@"getArchiveOffice"]||[methName isEqualToString:@"GwArchiveSearch"]||[methName isEqualToString:@"SwArchiveSearch"]||[methName isEqualToString:@"getSwArchiveOffice"]){
        NSString *stra = [str stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
        NSString *strs = [stra stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
        NSString *strb = [strs stringByReplacingOccurrencesOfString:@"<soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\">" withString:@""];
        NSString *strc = [methName stringByAppendingString:@"Response"];
        NSString *strd = [NSString  stringWithFormat:[self defaultStringOne],strc];
        NSString *stre = [strb stringByReplacingOccurrencesOfString: strd withString:@""];
        NSString *strf = [NSString stringWithFormat:[self defaultStringTwo],strc];
        NSString *strg = [stre stringByReplacingOccurrencesOfString:strf withString:@""];
        NSString *strh = [strg substringFromIndex:38];
        NSString *strk = [strh stringByReplacingOccurrencesOfString:@"xmlns='exch.jhsx.gov.cn/data' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" withString:@""];
        string = strk;
    }else if ([methName isEqualToString:@"setSubmitWork"]||[methName isEqualToString:@"setRetStaffList"]|| [methName isEqualToString:@"setStaffListDeliver"] || [methName isEqualToString:@"setSignIn"] ||[methName isEqualToString:@"setSaveWork"]){
            NSString *stra = [str stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
            NSString *strs = [stra stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
            NSString *strb = [strs stringByReplacingOccurrencesOfString:@"<soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\">" withString:@""];
            
            NSString *strc = [methName stringByAppendingString:@"Response"];
            NSString *strd = [NSString  stringWithFormat:[self defaultStringOne],strc];
            NSString *stre = [strb stringByReplacingOccurrencesOfString: strd withString:@""];
            
            NSString *strf = [NSString stringWithFormat:[self defaultStringTwo],strc];
            NSString *strg = [stre stringByReplacingOccurrencesOfString:strf withString:@""];
            NSString *strh = [strg substringFromIndex:38];
            NSString *strk = [strh stringByReplacingOccurrencesOfString:@"xmlns='exch.jhsx.gov.cn/data' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" withString:@""];
            string = strk;
        }
    return string;
}


+(NSString*)defaultStringOne{
    NSString *soapBody=@"<soapenv:Body><ns:%@ xmlns:ns=\"http://ws.apache.org/axis2\"><ns:return>";
    return soapBody;
}
+(NSString*)defaultStringTwo{
    NSString *soapBody=@"</ns:return></ns:%@></soapenv:Body></soapenv:Envelope>";
    return soapBody;
}

+(NSString*)stringWithFormatString:(NSArray*)params method:(NSString*)method{
    
    NSString * paramsString = [self paramsFormatString:params];
    NSString * paramsString2 = [self methName:method nameSpace:KNameSpace bodyString:paramsString];
    
    return [NSString stringWithFormat:[self defaultSoapMesage],paramsString2];
}
/*
函数名字：paramsFormatString
功能：构造 子元素文本的格式
参数：子元素和元素文本
返回值：元素和文本字符串
*/
+(NSString*)paramsFormatString:(NSArray*)params{
    NSMutableString *xml=[NSMutableString stringWithFormat:@""];
    for (NSDictionary *item in params) {
        NSString *key=[[item allKeys] objectAtIndex:0];
        [xml appendFormat:@"<%@>",key];
        [xml appendString:[item objectForKey:key]];
        [xml appendFormat:@"</%@>",key];
    }
//NSMutableString *xml=[NSMutableString stringWithFormat:@""];
//    for (NSDictionary *item in params) {
//        NSString *key=[[item allKeys] objectAtIndex:0];
//        [xml appendFormat:@"<SuggestService:%@>",key];
//        [xml appendString:[item objectForKey:key]];
//        [xml appendFormat:@"</SuggestService:%@>",key];
//    }
    return xml;
}

/*
 函数名字：paramString:(NSString *)methName andString:(NSString *)nameSpace andThree:(NSString *)Body
 功能：构造 元素和属性的格式
 参数：函数名字，命名空间，子元素
 返回值：元素和属性字符串
 */
+(NSString *)methName:(NSString *)methName nameSpace:(NSString *)nameSpace bodyString:(NSString *)Body
{
    NSMutableString *xml=[NSMutableString string];
    [xml appendFormat:@"<web:%@>",methName];
    [xml appendFormat:@"%@",Body];
    [xml appendFormat:@"</web:%@>",methName];

//    NSMutableString *xml=[NSMutableString string];
//    [xml appendFormat:@"<SuggestService:%@>",methName];
//    [xml appendFormat:@"%@",Body];
//    [xml appendFormat:@"</SuggestService:%@>",methName];

    return xml;
}


+(NSString*)defaultSoapMesage{


NSString *soapBody=@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
    "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"  xmlns:web=\"http://webservice.jfinal.flysoft.com/\">\n"
    "<soapenv:Body>%@</soapenv:Body>\n"
    "</soapenv:Envelope>\n";

// NSString *soapBody=@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
////    "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">\n"
//    "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\">\n"
//    "<soap:Body>%@</soap:Body>\n"
//    "</soap:Envelope>\n";

//NSString *soapBody=@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
//    "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\"xmlns:SuggestService=\"http://ws.apache.org/axis2\" xsl:version=\"1.0\">\n"
//    "<soap:Body>%@</soap12:Body>\n"
//    "</soap:Envelope>\n";



    return soapBody;
}

#pragma mark 文件下载
+(void)downFileWith:(NSString*)url success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure{
   NSURL * URL = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest * request = [NSURLRequest requestWithURL:URL];
    NSOperationQueue * mainqueue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:mainqueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
      
//        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//        NSLog(@"%@",connectionError.localizedDescription);
    }];
}

+(void)requestWithURL:(NSString*)url arrays:(NSArray*)arrays  method:(NSString*)method success:(void(^)(id JSON))success failure:(void(^)(NSError *error))failure{
    NSString *soapMessage = [self stringWithFormatString:arrays method:method];



    NSURL *url1 = [NSURL URLWithString:url];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url1];
    [theRequest setValue:[NSString stringWithFormat:@"%zd", soapMessage.length] forHTTPHeaderField:@"Content-Length"];

    theRequest.timeoutInterval = 30.0;
//    [theRequest addValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theRequest setHTTPMethod:@"POST"];
       [theRequest addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest addValue:[NSString stringWithFormat:@"%@/%@",KNameSpace,method] forHTTPHeaderField:@"SOAPAction"];

    
    NSOperationQueue * operationQueue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:theRequest queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            NSString * result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//            NSLog(@"result = %@",result);

            NSString * jsonString  = [self jsonStringWithFormatString:result];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                 success(jsonString);
            });
           
            

        }else if (connectionError){
            dispatch_async(dispatch_get_main_queue(), ^{
            if (![[NSString stringWithFormat:@"%@",connectionError.localizedDescription]isEqualToString:@"未能找到使用指定主机名的服务器。"]){
                [[UIApplication sharedApplication].keyWindow.rootViewController.view makeToast:connectionError.localizedDescription];}
                
                failure(connectionError);
            });
         
        }
        
    }];

    
}
+(NSString*)jsonStringWithFormatString:(NSString*)resultString{
    
    NSString * result = nil;
    if (resultString && [resultString rangeOfString:@"<return>"].location != NSNotFound) {
        NSArray * tempArray = [resultString componentsSeparatedByString:@"<return>"];
        NSString * tempString= [tempArray lastObject];
        NSArray * resultArray = [tempString componentsSeparatedByString:@"</return>"];
        result = [resultArray firstObject];
        
        if (result.length != 0) {
        
        result = [result stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    //去掉html的填充格式
    
        result = [result stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
        result = [result stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
//          result =  [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:NULL];
//NSLog(@"%@",result);
                    result =  [NSJSONSerialization JSONObjectWithData:[result dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:NULL];
//NSLog(@"%@",result);
        }
    }
   
    return result;
}



@end
